import React, { Component } from 'react'
import { Modal, Steps, Form, Input, Select, Button, Space, message, Tooltip } from 'antd'
import { CloseOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons'

import request from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig.js'

import './index.less'

const { organizationManagement: { certificateCreate, certificateUpdate }} = address
const { Step } = Steps
const { Option } = Select

class CreateModal extends Component {
  constructor(props) {
    super(props)
    this.flag = props.flag
    const { form1data, form2Val } = this.init(props.record)
    this.state = {
      current: this.flag === 'update' ? 1 : 0,
      form1data,
      form2data: {},
      form2Val,
      loading: false,
    }
  }

  /**
   *
   * @param {初始化数据} data
   * @returns
   */
  init = (data = {}) => {
    const infoList = (data.attributes || '').split(',').reduce((arr, v) => {
      const [first, last] = v.replace(':ecert', '').split('=')
      first && last && arr.push({
        first,
        last,
      })
      return arr
    }, [])
    const form2Val = {
      infoList,
    }
    const form1data = {
      description: data.remark,
      cert_type: data.type,
      cert_id: data.identity,
    }
    return {
      form2Val,
      form1data,
    }
  }

  handleOk = () => {
    const { current } = this.state
    if (current === 0) {
      // 存储第一步表单结果
      this.btn1.click()
    } else {
      this.btn2.click()
    }
  }

  handleCancel = () => {
    const { current } = this.state
    if (current === 0) {
      const { createCerClose } = this.props
      createCerClose && createCerClose()
    } else {
      this.setState({
        current: 0,
      })
    }
  }

  firstStepForm = values => {
    this.setState({
      current: 1,
      form1data: values,
    })
  }

  onFinish = values => {
    let obj = {}
    const data = (values.infoList || []).filter(v => v.first && v.last)
    data.map(item => {
      obj[item.first.trim()] = item.last.trim()
    })
    this.setState({
      form2data: obj,
      form2Val: values,
    }, () => {
      this.createFn()
    })
  };

  onValuesChange = (changedValues, allValues) => {
    this.setState({
      form2Val: allValues,
    })
  }

  formatData = (data) => {
    var str = ''
    for (var i in data) {
      str += (i + '=' + data[i] + ':ecert' + ',')
    }
    str = str.slice(0, str.length - 1)
    return str
  }

  createFn = () => {
    const { form1data, form2data } = this.state
    const { orgId, createCerClose, record } = this.props
    const result = this.formatData(form2data)
    const options = {
      orgId,
      ...form1data,
      attrs: result,
    }
    this.setState({
      loading: true,
    })
    request().post(this.flag === 'update' ? certificateUpdate.format({ id: record.id }) : certificateCreate, options).then(({ status }) => {
      this.setState({
        loading: false,
      })
      if (status === 200) {
        message.success(`证书${this.flag === 'update' ? '修改' : '创建'}中`)
        this.setState({
          current: 0,
        })
        createCerClose && createCerClose()
      }
    })
  }

  DynamicFieldSet = () => {
    const { form2Val } = this.state
    return (
      <div className="dynamic-field">
        <div id="dynamic-label" className="dynamic-label">
          证书信息：
          <Tooltip getPopupContainer={() => document.getElementById('dynamic-label')} placement="right"
            title={
              <div className="tip-content">
                <p>基于属性的访问控制</p>
                <p>Hyperledger Fabric支持使用基于属性的访问控制（ ABAC , Attribute 一 Based Access Control ）来控制用户的访问权限．在进行用户的身份注册时，登录证书（ ECert ）可以包含一个或多个属性名称和值，链码运行时可以提取属性值来进行访问控制决策。例如，您正在开发一个名为app1的应用，只有app1的管理员才可以访问一个特定的chaincode操作。您的chaincode可以根据调用者的证书中是否包含的 app1Admin属性以及该属性值是否为“true”来决定是否允许访问。</p>
              </div>
            }>
            <span className="form-tip"><ExclamationCircleOutlined />说明</span>
          </Tooltip>

        </div>
        <Form
          className="dynamic-form"
          name="form2"
          onFinish={this.onFinish}
          autoComplete="off"
          initialValues={form2Val}
          onValuesChange={this.onValuesChange}
        >
          <Form.List name="infoList">
            {(fields, { add, remove }) => {
              return (
                <div>
                  {fields.map(field => (
                    <Space key={field.key} style={{ display: 'flex', marginBottom: 12 }} align="start">
                      <Form.Item
                        {...field}
                        name={[field.name, 'first']}
                        fieldKey={[field.fieldKey, 'first']}
                      >
                        <Input style={{ width: '160px' }} maxLength={50} placeholder="请输入属性名" />
                      </Form.Item>
                                        -
                      <Form.Item
                        {...field}
                        name={[field.name, 'last']}
                        fieldKey={[field.fieldKey, 'last']}
                      >
                        <Input style={{ width: '160px' }} maxLength={50} placeholder="请输入属性值" />
                      </Form.Item>
                      <CloseOutlined
                        onClick={() => {
                          remove(field.name)
                        }}
                      />
                    </Space>
                  ))}
                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={() => {
                        add()
                      }}
                      block
                      style={{ width: '345px', fontSize: '12px' }}
                    >
                      <PlusOutlined />添加证书信息
                    </Button>
                  </Form.Item>
                </div>
              )
            }}
          </Form.List>
          <Button ref={ref => this.btn2 = ref} className="form2-btn" htmlType="submit"></Button>
        </Form>
      </div>

    )
  };

  render() {
    const { current, form1data, loading } = this.state
    return (
      <Modal
        className="create-c-modal common-normal-modal"
        getContainer={() => document.getElementById('certificate-page')}
        title={`${this.flag === 'update' ? '修改证书' : '创建证书'}`}
        visible={this.props.visible}
        onOk={this.handleOk}
        onCancel={this.props.createCerClose}
        cancelButtonProps={{
          onClick: this.handleCancel,
        }}
        okButtonProps={{
          loading,
        }}
        cancelText={current === 0 ? '取消' : '上一步'}
        okText={current === 0 ? '下一步' : this.flag === 'update' ? '修改' : '创建'}
        centered
        maskClosable={false}
      >
        <div className="create-steps">
          <Steps labelPlacement="vertical" current={current}>
            <Step title="第一步" icon={<div className="steps-icon"><span className="steps-icon-label">01</span></div>} />
            <Step title="第二步" icon={<div className="steps-icon"><span className="steps-icon-label">02</span></div>} />
          </Steps>
        </div>
        <div className="steps-content">
          {
            current === 0 &&
            <Form
              className="step1-form"
              onFinish={this.firstStepForm}
              labelCol={{ span: 5 }}
            >
              <Form.Item
                label="证书类型"
                name="cert_type"
                rules={[
                  { required: true, message: '请输入证书类型' },
                ]}
                initialValue={form1data.cert_type || null}
              >
                <Select
                  placeholder="请选择证书类型"
                  allowClear
                  disabled={this.flag === 'update'}
                >
                  <Option value="client">client</Option>
                  <Option value="admin">admin</Option>
                </Select>
              </Form.Item>
              <Form.Item
                label="证书标识"
                name="cert_id"
                rules={[
                  {
                    required: true, message: '请输入证书标识',
                  },
                  {
                    pattern: /^[\da-z\-_]{1,15}$/,
                    message: '证书标识字段由小写字母，数字，短连接符(-)，下划线(_)组成',
                  },
                  () => ({
                    validator(rule, value) {
                      if (value) {
                        if (!/^[\da-z]/.test(value) || !/[\da-z]$/.test(value)) {
                          return Promise.reject('首尾字符只能是数字和字母')
                        }
                      }
                      if (!value || value.trim() !== 'admin') {
                        return Promise.resolve()
                      }
                      return Promise.reject('标识不允许为admin')
                    },
                  }),
                ]}
                initialValue={form1data.cert_id || ''}
              >
                <Input disabled={this.flag === 'update'} maxLength={15} placeholder="请输入证书标识，禁止使用admin" />
              </Form.Item>
              <Form.Item
                label="备注"
                name="description"
                initialValue={form1data.description || ''}
              >
                <Input.TextArea disabled={this.flag === 'update'} rows={5} maxLength={20} placeholder="请输入备注, 长度不超过20个字符" />
              </Form.Item>
              <Button ref={ref => this.btn1 = ref} className="form1-btn" htmlType="submit"></Button>
            </Form>
          }
          {
            current === 1 && this.DynamicFieldSet()
          }
        </div>
      </Modal>
    )
  }
}

export default CreateModal
